package com.nami.gate.process.upmsg;

import com.google.protobuf.ByteString;
import com.nami.gate.config.RpcConfig;
import com.nami.gate.constants.ChannelConstants;
import com.nami.gate.external.basic.constants.UpTopicConst;
import com.nami.gate.middleware.mq.MqSender;
import com.nami.im.network.model.packet.v2.Packet;
import com.nami.transport.proto.codec.MqTransMsg;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PublishAckProcess implements PacketProcessor {

    private static final Logger log = LoggerFactory.getLogger(PublishAckProcess.class);

    private MqSender mqSender;
    private RpcConfig rpcConfig;


    public PublishAckProcess(MqSender mqSender, RpcConfig rpcConfig) {
        this.mqSender = mqSender;
        this.rpcConfig = rpcConfig;
    }

    @Override
    public void process(Channel channel, Packet packet) throws Exception {
        try {
            mqSender.send(UpTopicConst.QOS_TOPIC, genMqTransMsgBytes(channel, packet));
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("发送publish消息失败, {}", ex.getMessage());
        }
    }

    private byte[] genMqTransMsgBytes(Channel channel, Packet packet) {
        String userId = (String) channel.attr(AttributeKey.valueOf(ChannelConstants.USER_ID)).get();
        String appKey = (String) channel.attr(AttributeKey.valueOf(ChannelConstants.APP_KEY)).get();
        String instanceId = (String) channel.attr(AttributeKey.valueOf(ChannelConstants.INSTANCE_ID)).get();
        String platform = (String) channel.attr(AttributeKey.valueOf(ChannelConstants.PLATFORM)).get();

        MqTransMsg.Gate2RouterPublishAckMsg  publishMsg = MqTransMsg.Gate2RouterPublishAckMsg.newBuilder()
            .setData(ByteString.copyFrom(packet.getBody()))
            .setQos(packet.getQos())
            .setUserId(userId)
            .setAppKey(appKey)
            .setInstanceId(instanceId)
            .setConnectId(rpcConfig.getConnectId())
            .setPlatform(platform)
            .setTimestamp(System.currentTimeMillis())
            .build();
        return publishMsg.toByteArray();
    }


}
